import time
from selenium import webdriver
from selenium.webdriver.common.by import By

# 验证码识别
import ddddocr

# 显示等待，更加智能
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 提供键盘按键的支持，比如：RETURN, F1, ALT等
from selenium.webdriver.common.keys import Keys

from utils import is_login, load_cookies, save_cookies

driver = webdriver.Firefox()
load_cookies(driver)

# 判断是否已经登录
# if is_login(driver) is False:
driver.get("http://106.38.235.201:7080/portal/")

# 操作cookies
cookies = driver.get_cookies()
for cookie in cookies:
    driver.add_cookie(cookie)
    # 需要刷新页面，向服务器发送cookies
    driver.refresh()

driver.find_element(By.ID, "username").send_keys("43132220201")
driver.find_element(By.ID, "password").send_keys("Tmxczx@1234")

# 获取验证码并保存
imgCode = driver.find_element(By.ID, "jcaptcha")
imgCode.screenshot("jcaptcha.jpg")
# 验证码识别
ocr = ddddocr.DdddOcr()
with open("jcaptcha.jpg", "rb") as f:
    img_bytes = f.read()
    res = ocr.classification(img_bytes)
    print(res)
codeInput = driver.find_element(By.ID, "jcaptcha_response").send_keys(res)

# 登录
driver.find_element(By.ID, "loginBut").click()

# 浏览器关闭之前保存cookies
save_cookies(driver)
time.sleep(2)
driver.close()
# else:
#     try:
#         element = WebDriverWait(driver, 10).until(
#             EC.presence_of_element_located((By.NAME, "menuIcon1"))
#         )
#         if element:
#             print("我已经成功等待")
#         else:
#             print("失败是我")
#     finally:
#         driver.quit()
#     print(666)
